package com.jinlejia.erp.ui.mine.myinfo;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.SaveCookieBean;
import com.jinlejia.erp.databinding.ActivityShowCropperBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DbUtil;
import com.jinlejia.erp.utils.RxUpLoad;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

import static com.jinlejia.erp.base.ApiConfig.IMG_UPLOAD_HEADER;

/**
 * 展示裁剪图片 上传
 */

public class ShowCropperActivity extends AppCompatActivity {
    private ProgressDialog progressDialog;
    private JSONObject Object = new JSONObject();

    private ActivityShowCropperBinding binding;

    public static void startWithUri(@NonNull Context context, @NonNull Uri uri) {
        Intent intent = new Intent(context, ShowCropperActivity.class);
        intent.setData(uri);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_show_cropper);
        binding.setEvent(this);
        initView();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        if (getIntent().getData() != null) {
            binding.imageHeader.setImageURI(getIntent().getData());
        }
    }

    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.up_load:
                progressDialog = new ProgressDialog(ShowCropperActivity.this, "上传中...");
                progressDialog.show();
                try {
                    File file = new File(new URI(getIntent().getData().toString()));
                    compressWithRx(file);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    /**
     * 压缩单张图片 RxJava 方式
     */
    private void compressWithRx(File file) {
        Luban.get(this)
                .load(file)
                .putGear(Luban.THIRD_GEAR)
                .asObservable()
                .flatMap((Func1<File, Observable<String>>) file1 -> {
                    Map<String, String> header = new HashMap<>();
                    header.put("token", ACache.get(ShowCropperActivity.this).getAsString("token") == null ? "" : ACache.get(ShowCropperActivity.this).getAsString("token"));
                    header.put("cookie", null == DbUtil.getDB(ShowCropperActivity.this).single().queryById(200, SaveCookieBean.class) ? "" : DbUtil.getDB(ShowCropperActivity.this).single().queryById(200, SaveCookieBean.class).getCookie());

                    return RxUpLoad.get(ShowCropperActivity.this)
                            .url(ApiConfig.IMG_UPLOAD)
                            .file(file1)
                            .fileName(System.currentTimeMillis() + ".jpg")
                            .key("uploadFile")
                            .header(header)
                            .asObservable();
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    JSONObject jsonObject = JSON.parseObject(s);
                    if (jsonObject.get("code").toString().equals("200")) {
                        Object.put("imageUrl", jsonObject.get("data"));
                        if (!TextUtils.isEmpty(jsonObject.get("data").toString())) {
                            submit();
                        }
                    } else {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        CustomToast.showToast(ShowCropperActivity.this, jsonObject.get("message").toString(), 1500);
                    }
                });
    }

    //上传
    private void submit() {
        OkHttpUtils
                .postString()
                .url(IMG_UPLOAD_HEADER)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(Object.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(ShowCropperActivity.this, response, null)) {
                            EventBus.getDefault().post("s", "IMG_UPLOAD_HEADER");
                            CustomToast.showToast(getApplicationContext(), "上传成功", 1500);
                            finish();
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
